package com.china08.yxyapi.api.manage.tec.teaching.weikecheng.weike;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyKnowledge;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResourceForEsReindex;
import com.china08.yxyapi.entity.db.res.YxyResWeikeKnow;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyKnowledgeRepository;
import com.china08.yxyapi.repository.db.YxyResResourceForEsReindexRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResWeikeKnowRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.util.EsResourceUpdateUtil;
import com.china08.yxyapi.util.WeikeCoverUntil;
import com.china08.yxyapi.util.YXGetVideoInfoUtil;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---发布微课(除视频外的其他信息)
 * 
 */
@CrossOrigin
@RestController
public class WeikechengCrtController extends YxyApiBaseController {

    @Autowired
    private YxyResResourceRepository weikeRepository;

    @Autowired
    private YxyResWeikeKnowRepository weikeknowRepository;

    @Autowired
    private YxyKnowledgeRepository knowRepository;

    @Autowired
    private YxyResResourceForEsReindexRepository esReindexRepository;

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @Autowired
    private YXGetVideoInfoUtil yXGetVideoInfoUtil;

    @ApiOperation(value = "发布微课")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/weikecheng/weike", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req,
            RespModel respModel) throws Exception {

        YxyProfile yxyProfile = getProfile(request, response);
        String userId = yxyProfile.getId();
        String schoolId = yxyProfile.getSchoolId();
        YxyResResource weikeResource = null;
        // true 没换视频 false换了视频
        Boolean edit = false;
        // 编辑微课
        if (StringUtils.isNotBlank(req.weikeId)) {
            // 微课
            weikeResource = weikeRepository.findById(req.weikeId);
            Assert.notNull(weikeResource, "微课已不存在");
            // 教研更改
            if (!"4028e4ef54f20e350154ffa02cad5496".equals(userId)) {
                Assert.isTrue(StringUtils.equals(userId, weikeResource.getUploaderId()), "这不是您的微课");
            }
            edit = weikeResource.getMd5().equals(req.md5);
        }
        // 新建微课
        if (weikeResource == null || !edit) {
            if (weikeResource == null) {
                weikeResource = new YxyResResource();
            }
            List<YxyResResource> findByMd5 = weikeRepository.findByMd5OrderByUploadTimeAsc(req.md5);
            Integer duration = 0;
            Integer convertStatus = 0;
            Integer fileSize = 0;
            String md5 = req.md5;
            if (CollectionUtils.isNotEmpty(findByMd5)) {
                YxyResResource findByMd5Resource = findByMd5.get(0);
                duration = findByMd5Resource.getDuration();
                convertStatus = findByMd5Resource.getConvertStatus();
                fileSize = findByMd5Resource.getFileSize();
                md5 = findByMd5Resource.getMd5();
            }
            if (duration == 0) {
                Long duration1 = yXGetVideoInfoUtil.getDuration(uploadBasePath + req.location) / 1000;
                if (duration1 != null) {
                    duration = Integer.valueOf(duration1 + "");
                }
            }
            if (fileSize == 0) {
                File file = new File(uploadBasePath + req.location);
                if (file.exists() && file.isFile()) {
                    fileSize = Integer.valueOf(file.length() + "");
                }
                file = null;
            }
            weikeResource.setMd5(md5);
            weikeResource.setDuration(duration);
            weikeResource.setLocation(req.location);
            convertStatus = convertStatus == 2 ? convertStatus : 0;
            weikeResource.setConvertStatus(convertStatus);
            weikeResource.setFileSize(fileSize);
            weikeResource.setExtension(req.ext);
            //
            weikeResource.setFormatId("FMT04");
            weikeResource.setFormatName("视频");
            // 微课信息
            weikeResource.setTypeId("yx14");
            weikeResource.setTypeName("微课");
            // 上传者信息 使用云校接口
            weikeResource.setUploaderId(userId);
            weikeResource.setUploaderName(yxyProfile.getUserNick());
            // 作者
            weikeResource.setAuthor(yxyProfile.getUserNick());
            // 学校信息 使用云校接口
            weikeResource.setUploaderSchoolId(schoolId);
            weikeResource.setUploaderSchoolName(yxyProfile.getSchoolName());
            // 省,市,区
            weikeResource.setProvinceCode(yxyProfile.getSchoolAreaIdProvince());
            weikeResource.setCityCode(yxyProfile.getSchoolAreaIdCity());
            weikeResource.setDistrictCode(yxyProfile.getSchoolAreaIdDistrict());
            //
            weikeResource.setIsYxYunRes(0);
            weikeResource.setIsYxView(0);
        }
        // 微课信息
        weikeResource.setTitle(req.title);
        weikeResource.setIntro(req.intro);
        weikeResource.setViewScope(req.viewScope);
        weikeResource.setStatus(req.viewScope == 0 ? 1 : 0);
        if (StringUtils.isBlank(req.cover)) {
            // 默认图片
            weikeResource.setCover(WeikeCoverUntil.getCover(req.subject));
        } else {
            weikeResource.setCover(req.cover);
        }
        weikeResource.setIsDelete(0);
        weikeResource = weikeRepository.save(weikeResource);

        // 关联知识点
        List<Integer> knowList = req.knoLevel3Id;
        boolean flag = false;
        if (CollectionUtils.isNotEmpty(knowList)) {
            flag = true;
            weikeknowRepository.deleteByWeikeId(req.weikeId);
        }
        for (Integer knowThreeId : knowList) {
            flag = true;
            YxyResWeikeKnow weikeKnow = new YxyResWeikeKnow();
            // 三级
            YxyKnowledge knowThree = knowRepository.findById(knowThreeId);
            // 二级
            Integer knoLevel2Id = knowThree.getParentId();
            YxyKnowledge knowTwo = knowRepository.findById(knoLevel2Id);
            // 一级
            Integer knoLevel1Id = knowTwo.getParentId();
            YxyKnowledge knowOne = knowRepository.findById(knoLevel1Id);

            weikeKnow.setKnowOneLevelId(knoLevel1Id + "");
            weikeKnow.setKnowOneLevelName(knowOne.getName());

            weikeKnow.setKnowTwoLevelId(knoLevel2Id + "");
            weikeKnow.setKnowTwoLevelName(knowTwo.getName());

            weikeKnow.setKnowId(knowThree.getId());
            weikeKnow.setKnowName(knowThree.getName());
            // 学段,学科
            weikeKnow.setStage(req.stage);
            weikeKnow.setStageName(req.stageName);
            weikeKnow.setWeikeSubject(req.subject);
            weikeKnow.setWeikeSubjectName(req.subjectName);
            weikeKnow.setWeikeId(weikeResource.getId());
            weikeknowRepository.save(weikeKnow);
        }

        if (flag) {
            YxyResResourceForEsReindex esIndex = new YxyResResourceForEsReindex();
            esIndex.setResourceId(weikeResource.getId());
            esReindexRepository.save(esIndex);
        }
        // 重建索引
        EsResourceUpdateUtil.updateEsResoure(req.weikeId);
        respModel = new RespModel();
        respModel.setMessage("发布微课成功");
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {

        public String location;// 视频存储地址

        public String md5; // 视频md5

        public String ext; // 文件后缀

        public String weikeId;// 微课id

        public String title;// 微课名称

        public String intro;// 简介

        public String stage;// 学段

        public String stageName;// 学段名称

        public String subject;// 科目

        public String subjectName;// 科目名称

        public Integer viewScope;// 共享范围

        public String cover;// 封面

        public List<Integer> knoLevel3Id;// 三级知识点ids

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(weikeId, null), "微课id不能为空");
            Assert.notNull(StringUtils.defaultIfBlank(title, null), "请填写标题");
            Assert.notNull(StringUtils.defaultIfBlank(intro, null), "请填写微课简介");
            Assert.notNull(StringUtils.defaultIfBlank(stage, null), "请选择学段");
            Assert.notNull(StringUtils.defaultIfBlank(stageName, null), "请选择学段");
            Assert.notNull(StringUtils.defaultIfBlank(subject, null), "请选择学科");
            Assert.notNull(StringUtils.defaultIfBlank(subjectName, null), "请选择学科");
            Assert.notNull(viewScope, "请选择共享范围");
            Assert.isTrue(CollectionUtils.isNotEmpty(knoLevel3Id), "请选择三级知识点");
        }

    }

    protected static class RespModel extends YxyApiRespModel {

    }
}
